<template>
	<view class="main">
		<header>
			<button class="button-cancel" :style="{background:`linear-gradient(10deg, ${theme.primary} 5%, ${theme.primaryLight}, ${theme.primary} 95%)`}" @tap="cancel">取消</button>
			<button v-if="showDtl" class="button-complete" :style="{background:`linear-gradient(10deg, ${theme.primary} 5%, ${theme.primaryLight}, ${theme.primary} 95%)`}" @tap="complete">完成</button>
		</header>
		<main>
			<view class="timer" :style="{color:theme.primary}">{{nums}}</view>
		</main>
		<footer>
			<view class="footer-left" v-if="showDtl">
				<view class="play-border" :style="{borderColor: theme.primary}">
					<jIcon name="icon-delete" size="70"></jIcon>
				</view>
				<text>回删</text>
			</view>
			<view class="footer-item">
				<view class="footer-cover" v-if="!showPlay"></view>
				<view class="play-border" :style="{borderColor: theme.primary}">
					<jIcon :name="record.src" size="70" @tap="isRecord = !isRecord"></jIcon>
				</view>
				<text>{{record.text}}</text>
			</view>
			<view class="footer-right" v-if="showDtl">
				<view class="play-border" :style="{borderColor: theme.primary}">
					<jIcon :name="play.src" size="70" @tap="isPlay = !isPlay"></jIcon>
				</view>
				<text>{{play.text}}</text>
			</view>
		</footer>
		<image v-if="showMusic" src="../../static/icon/music.png" v-bind:class="musicStyle" @tap="this.isPlayMusic = !this.isPlayMusic"></image>
	</view>
</template>

<script>
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	export default{
		name:'recordVoice',
		props:{
			Id: String,
			isSingleAudio:Boolean
		},
		data(){
			return{
				theme: this.$theme,
				//时间文字
				nums:'00:00',
				//完成、回删、播放按钮显示标记
				showDtl:false,
				//录音按钮数据
				record:{src:'icon-recordBtn', text:'点击录音'},
				//播放按钮数据
				play:{src:'icon-play', text:'点击播放'},
				//当前录制的音频
				voice:'',
				//当前录制的音频时间，单位：s
				duration:0,
				//录音按钮遮罩层显示标记，是否可点击录音按钮
				showPlay: true,
				//最大录音时长，单位：s
				audioLength: 0,
				//音乐卡片动画
				musicStyle:['music'],
				//音乐动画是否触发
				isPlayMusic: false,
				//背景音乐组件
				bgAudioMannager: '',
				isRecord: false,
				isPlay: false
			}
		},
		computed:{
			showMusic(){
				return this.Id&&this.isSingleAudio;
			}
		},
		watch:{
			isPlayMusic(e){
				if(!this.showMusic)return
				if(e){
					this.bgAudioMannager.play()
					this.musicStyle = ['music', 'music-roate']
				}else{
					this.bgAudioMannager.stop()
					this.musicStyle = ['music']
				}
			},
			voice(e){
				if(e){
					this.showDtl = true
				}else{
					this.showDtl = false
				}
			},
			isRecord(e){
				try{
					if(e){						
						recorderManager.start({
							format:'mp3',
							encodeBitRate: 44100,
							sampleRate: 8000,
							duration: this.audioLength * 1000
						})
					}else{						
						recorderManager.stop()
					}
				}catch(e){
					//TODO handle the exception
					console.log(e)
				}
				
			},
			isPlay(e){
				if(e){
					innerAudioContext.src = this.voice;
					innerAudioContext.play()
				}else{
					innerAudioContext.stop()
				}
			}
		},
		created() {
			this.initConfig()
			//存在用户Id,则存在背景音乐，属美篇编辑录音，可以初始化背景音乐
			if(this.Id&&this.isSingleAudio){
				this.initBack()
			}
			recorderManager.onStart(()=>{		
				this.record.src = 'icon-suspend'
				this.record.text = '停止录音'
				this.isPlayMusic = true
				this.showDtl = false
				this.timing()
			})
			recorderManager.onStop(resp => {
				this.record.src = 'icon-recordBtn'
				this.record.text = '点击录音'
				this.isPlayMusic = false
				this.stopTiming()
				let recordTime = resp.duration/1000
				if(recordTime > this.audioLength){
					uni.showToast({
					    title: '音频录制失败，录制时间不可以太长哦',
						icon: 'none',
					    duration: 2000
					})
				}
				else if(recordTime < 2){
					uni.showToast({
					    title: '音频录制失败，录制时间不可以太短哦',
						icon: 'none',
					    duration: 2000
					})
				}
				else{
					this.voice = resp.tempFilePath
					this.duration = recordTime
				}
			})
			innerAudioContext.onPlay(()=>{
				this.timing(innerAudioContext.duration)
				this.play.src = 'icon-pause'
				this.showPlay = false
				this.play.text = '停止播放'
			})
			innerAudioContext.onEnded(()=>{
				this.play.src = 'icon-play'
				this.play.text = '点击播放'
				this.showPlay = true
				this.stopTiming()
			})
			innerAudioContext.onStop(()=>{
				this.play.src = 'icon-play'
				this.play.text = '点击播放'
				this.showPlay = true
				this.stopTiming()
			})
			innerAudioContext.onError(function(e){
				console.log(e)
			})
		},
		destroyed(){
			recorderManager.stop()
			if(this.bgAudioMannager){
				this.bgAudioMannager.stop()
			}
			innerAudioContext.stop()
		},
		methods:{
			//拉取录音配置信息
			initConfig(){
				this.$http.request({
					url: 'api/Essay/GetEssayConfig',
					method: 'GET',
					data:{
						EssayType: 2
					}
				}).then(resp=>{
					this.audioLength = resp.audioLength
				})
			},
			//初始化背景音乐
			initBack(){
				this.$http.request({
					url: 'api/Essay/GetTemplateAudio',
					method: 'GET',
					data:{
						Id: this.Id
					}
				}).then(resp=>{
					this.bgAudioMannager = uni.createInnerAudioContext();
					this.bgAudioMannager.src = resp.audioSrc
				})
				
			},
			//时间字符截取
			fixStr(num, length) {
				return ( "0" + num ).substr( -length );
			},
			//取消
			cancel(){
				this.$emit('cancel')
			},
			//完成
			complete(){
				let res = {voice:this.voice, duration:Math.ceil(this.duration)}
				this.$emit('save', res)
			},
			//回删
			del(){
				let that = this
				uni.showModal({
				    title: '提示',
				    content: '确认删除上一段音频？',
				    success: function (res) {
				        if (res.confirm) {
							if(that.voice){
								innerAudioContext.src = ''
								that.voice = ''
								that.nums = '00:00'
							}
				        } 
				    }
				});
			},
			//计时
			timing(duration){
				let minute, second;
				minute = second = 0;
				let millisecond = 0;
				this.timer = setInterval(() => {
				    millisecond = millisecond + 50;
				    if (millisecond >= 1000) {
				        millisecond = 0
				        second = second + 1
				    }
				    if (second >= 60) {
				        second = 0
				        minute = minute + 1
				    }
				    if (minute >= 60) {
				        minute = 0
				    }
				    this.nums = `${this.fixStr(minute, 2)}:${this.fixStr(second, 2)}`
				}, 50);
			},
			//停止计时
			stopTiming(){
				clearInterval(this.timer)
			}
		}
	}
</script>

<style lang="scss" scoped>
	@keyframes fadeIn{
		0%{
			transform: translateX(100vw);
		}
		100%{
			transform: translateX(0);
		}
	}
	.main{
		position: fixed;
		top: 0;
		left: 0;
		background-color: #fff;
		width: 100vw;
		height: 100vh;
		animation: 0.3s fadeIn;
		.music{
			width: 100rpx;
			height: 100rpx;
			position: absolute;
			right: 10rpx;
			top: 200rpx;
		}
		.music-roate{
			animation: 5s roate linear infinite;
		}
		@keyframes roate{
			0%{
				transform: rotate(0);
			}
			100%{
				transform: rotate(360deg);
			}
		}
		header{
			height: 6%;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			button{
				color: #fff;
				width: 130rpx;
				height: 50rpx;
				font-size: 30rpx;
				border-radius: 40rpx;
				margin: 0;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
		main{
			height: 70%;
			display: flex;
			justify-content: center;
			align-items: center;
			.timer{
				font-size: 80rpx;
				font-weight: bold;
			}
		}
		footer{
			width: 100vw;
			position: absolute;
			bottom: 0;
			display: flex;
			justify-content: space-around;
			align-items: center;
			padding-bottom: 100rpx;
			font-size: 30rpx;
			color: #545454;
			.footer-item, .footer-right, .footer-left{
				opacity: 1;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				position: relative;
				.footer-cover{
					width: 210rpx;
					height: 210rpx;
					border-radius: 50%;
					background-color: #fff;
					opacity: 0.4;
					position: absolute;
					top: 10rpx;
					left: -20rpx;
					z-index: 9;
				}
				.play-border{
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
					border: 1rpx solid transparent;
					display: flex;
					justify-content: center;
					align-items: center;
					margin: 20rpx;
					.icon-border{
						width: 70rpx;
						height: 70rpx;
						position: relative;
						overflow: hidden;
						.icon-del, .icon-play, .icon-stop{
							width: 100%;
							height: 100%;
							background-repeat: no-repeat;
							background-size: 100% 100%;
							position: relative;
							left: -100%;
						}
						.icon-del{
							background-image: url(../../static/icon/delete.png);
						}
					}
				}
				.play-border:active{
					opacity: 0.5;
				}
			}
		}
	}	
</style>
